#!/usr/bin/env python
# $Id: ne2sw.py 14 2008-07-09 21:02:02Z christophernhill $

import sys
import re

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def lineSubst(tup,ln):
   return re.sub(tup[0],tup[1],ln)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

doLoopLvl=0
iDoLvl=0
jDoLvl=0

# Tuples for regular expression substitution
blank=('','')
nm=(r'_cne\b','_csw')
iShiftLeft=(r'\bi\b','i-1')
iShiftRight=(r'\bI\b','I+1')
jShiftLeft=(r'\bj\b','j-1')
jShiftRight=(r'\bJ\b','J+1')

f=open(sys.argv[1],'r')
for line in f: # Scan each line of the file

   dos=re.findall(r'(?i)\bdo\s*\w*\s*=\b',line) # Find do loops on "line"
   if dos:
      for x in dos:
         doLoopLvl+=1 # For each DO that we encounter, increase the nesting
         if re.search(r'\bi\b',x): # Look for "do i ..."
            if iDoLvl != 0: print "ERROR: Too many levels of i-Loop"
            else: iDoLvl=doLoopLvl; i3=iShiftRight
         elif re.search(r'\bI\b',x): # Look for "do I ..."
            if iDoLvl != 0: print "ERROR: Too many levels of I-Loop"
            else: iDoLvl=doLoopLvl; i3=iShiftLeft
         if re.search(r'\bj\b',x): # Look for "do j ..."
            if jDoLvl != 0: print "ERROR: Too many levels of j-Loop"
            else: jDoLvl=doLoopLvl; j3=jShiftRight
         elif re.search(r'\bJ\b',x): # Look for "do J ..."
            if jDoLvl != 0: print "ERROR: Too many levels of J-Loop"
            else: jDoLvl=doLoopLvl; j3=jShiftLeft

   if iDoLvl != 0: line=lineSubst(i3,line) # Convert i indices
   if jDoLvl != 0: line=lineSubst(j3,line) # Convert j indices

   # Simplify the resulting mathematical expressions
   line=lineSubst( (r'\+1\s*\-\s*2','-1') ,line) # turn "+1-2" into "-1"
   line=lineSubst( (r'\+1\s*\-\s*1','')   ,line) # turn "+1-1" into ""
   line=lineSubst( (r'\+1\s*\+\s*1','+2') ,line) # turn "+1+1" into "+2"
   line=lineSubst( (r'\-1\s*\-\s*1','-2') ,line) # turn "-1-1" into "-2"
   line=lineSubst( (r'\-1\s*\+\s*1','')   ,line) # turn "-1+1" into ""
   line=lineSubst( (r'\-1\s*\+\s*2','+1') ,line) # turn "-1r+2" into "+1"
   line=lineSubst(nm,line)

   print line,

   enddos=re.findall(r'(?i)\benddo\b',line) # Find enddo's
   for x in enddos:
      if iDoLvl == doLoopLvl: iDoLvl=0; i3=blank # Stop future convertion
      if jDoLvl == doLoopLvl: jDoLvl=0; j3=blank # Stop future convertion
      doLoopLvl-=1   # Undo the nesting level for each enddo we encounter

if iDoLvl != 0: print "ERROR: i-loop not closed"
if jDoLvl != 0: print "ERROR: j-loop not closed"
